/*
 * Copyright 2023-2085 xujin <ceo@itgrail.com>
 *
 * Licensed under the Grail License, Version 1.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * https://itgrail.com/docs?id=3&catalogId=87
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.itgrail.pilot.app.service.impl;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.itgrail.pilot.app.service.DepartmentService;
import com.itgrail.pilot.infrastructure.tunnel.db.dao.DepartmentMapper;
import com.itgrail.pilot.infrastructure.tunnel.db.dataobject.DepartmentDO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;

/**
 * @Author Alex Du
 * @Date 2023/10/12 10:54
 */
@Service
public class DepartmentServiceImpl implements DepartmentService {

    @Autowired
    private DepartmentMapper departmentMapper;

    @Override
    public String getFullDeptPath(Integer deptId) {
        List<DepartmentDO> list = departmentMapper.selectList(new LambdaQueryWrapper<>());
        List<String> nameList = getNameList(deptId, list);
        nameList.sort(Comparator.naturalOrder());
        return CollUtil.join(nameList, "/");
    }

    private List<String> getNameList(Integer deptId, List<DepartmentDO> list) {
        List<String> nameList = new ArrayList<>();
        for (DepartmentDO dept : list) {
            if (deptId == dept.getId()) {
                nameList.add(dept.getName());
                nameList.addAll(getNameList(dept.getParentId(), list));
                break;
            }
        }
        return nameList;
    }


}
